package com.jifeng.br.pjj.bookreader.util.shiro;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author PangJunjie
 * @Date 2023/7/12/012
 */
@Configuration
public class ShiroConfig {
    @Bean("securityManager")
    public SecurityManager securityManager(Shiro2Realm realm) {
        /*初始化管理器*/
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        securityManager.setRememberMeManager(null);
        return securityManager;
    }

    @Bean("shiroFilter")
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        /*初始化工厂*/
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        /*配置管理器*/
        shiroFilter.setSecurityManager(securityManager);
        /*初始化过去方式的Map容器*/
        Map<String, Filter> filterMap = new HashMap<>();
        /*设置一个自定义的过滤规则名称，理论上可以用任意字符串，这个设置的规则名称表示必须登录才可以访问的规则，匿名规则的名称是固定的：anon*/
        filterMap.put("jifeng", new Shiro2Filter());
        shiroFilter.setFilters(filterMap);

        /*设置放行规则*/
        Map<String, String> filters = new HashMap<>();
        filters.put("/kaptcha.jpg", "anon");
        filters.put("/login", "anon");
        filters.put("/img/**", "anon");
        filters.put("/api/**", "anon");
        filters.put("/**", "jifeng");
        shiroFilter.setFilterChainDefinitionMap(filters);
        return shiroFilter;
    }
}
